#include"mystdio.h"
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<stdlib.h>
my_file  *my_fopen(const char*str,const char*mode)
{
    int fd=0;
    int flag=0;
    if(strcmp(mode,"r")==0)
    {
        flag|=O_RDONLY;
    }
    else if(strcmp(mode,"w")==0)
    {
        flag|=(O_CREAT|O_WRONLY|O_TRUNC);
    }
    else if(strcmp(mode,"a")==0)
    {
        
        flag|=(O_CREAT|O_WRONLY|O_APPEND);
    }
    else{}
    if(flag&O_CREAT)
    {
        fd=open(str,flag,0666);
    }
    else{
        fd=open(str,flag);
    }
    if(fd<0)
    {
        errno=2;
        return NULL;
    }

    my_file*fp=(my_file*)malloc(sizeof(my_file));
    if(fp==NULL)return NULL;
    fp->_fileno=fd;
    fp->_end=0;
    fp->_flag=LINE;
    return fp;
}
int my_fwrite(char*str,int num,my_file*stream)
{
    memcpy(stream->_buff+stream->_end,str,num);
    stream->_end+=num;
    if((stream->_flag&LINE)&&(stream->_buff[stream->_end-1]=='\n')&&stream->_end>0)
    {
        my_fflush(stream);
    }
    return 0;
}
int my_fflush(my_file*stream)
{
    if(stream->_end>0)
    {
        write(stream->_fileno,stream->_buff,stream->_end);
        stream->_end=0;

    }
    return 0;
}
int my_close(my_file*fp )
{
    fp->_end=0;
    return close(fp->_fileno);
}

